package com.rtsapp.server.platform.kongzhong;

import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.platform.IPlatformLoginService;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *  安趣登录SDK
 */
public class AnquLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger( AnquLoginService.class );

    //    "http://i.muomou.com/index.php/user/checkUser/uid/%s/vkey/%s/appid/%s/sign/%s"
    private static final String VERFILY_URL = AppConfig.getInstance().getAnQuUrl();
    //    "G100227"
    private static final String APP_ID_HONGJING = AppConfig.getInstance().getAnQuHongJingAppId();
    //    "c30211972da3cc93cd07f304fa90411b"
    private static final String APP_SECRET_HONGJING = AppConfig.getInstance().getAnQuHongJingAppSecret();

    //    "G100228"
    private static final String APP_ID_TANKEDAZHAN = AppConfig.getInstance().getAnQuTanKeZhanAppId();
    //    "cee74a486fccc49ac04fc33b1c8e11b1"
    private static final String APP_SECRET_TANKEDAZHAN = AppConfig.getInstance().getAnQuTanKeZhanAppSecret();

    @Override
    public String validateLoginToken(String token, String uid) {

        JSONObject info = JSONObject.parseObject(token);
        String userId = info.getString("token");
        String sid = info.getString("sid");
        String appId = info.getString("appid");
        String appSercret = null;

        if (appId.equals(APP_ID_HONGJING)) {
            appSercret = APP_SECRET_HONGJING;
        } else if (appId.equals(APP_ID_TANKEDAZHAN)) {
            appSercret = APP_SECRET_TANKEDAZHAN;
        }

        if (appSercret == null) {
            LOGGER.error(String.format("未找到 app_id [%s] 对应的 sercret "));
            return null;
        }

        String MD5STR = userId + sid + appId + appSercret;
        String MD5 = md5(MD5STR);
        String realURL = String.format(VERFILY_URL, userId, sid, appId, MD5);
        return valid(realURL)?"anqu_"+userId:null;
    }

    private boolean valid(String url) {

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpGet.setConfig(config);

        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpGet)){
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(result);
                int status = jsonObject.getIntValue("status");
                String message = jsonObject.getString("msg");
                if (status==0) {
                    return true;
                }
                LOGGER.error("安趣渠道登录失败,返回校验码: "+status+ " 错误信息:"+message);
            }
            return false;
        } catch (IOException e) {
            LOGGER.error("向易接服务器请求登录验证时出现异常:",e);
            return false;
        }
    }

    private String md5(String datastr) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(datastr.getBytes());
            return new BigInteger(1, messageDigest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String uid = "102107";
        String sid = "0fa15f27e3b22155987ea18a2ddecd40";
        AnquLoginService anquLoginService = new AnquLoginService();
        System.out.println(anquLoginService.validateLoginToken(sid, uid));
    }
}
